'''MisacaYoukuResolver

Author: Cauly Kan

Date: 2001.10.18

wiki: /wiki/MisacaConverterDesign.wiki

contact: cauliflower.kan@gmail.com

'''

import re
import json

from urllib import urlopen

def VideoSourceResolve(vid, part = 1):
    
    '''
    VideoSourceResovle
    fetch info from youku video for specifed vid.
    params: vid, expecting a string like "ykid=xxx", where xxx is a positive integer
    retval: None on error, otherwise a typical dict like {'timelength': 'xxx', 'vname': 'xxx', 'framecount': 'xxx', 'format': 'flv', 'urls': ['url1', 'url2']} would be returned.
    '''
    
    ret = {}
    
    m = re.match("^ykid=([0-9a-zA-Z]+)$", vid)
    
    if m is not None:
        
        vid = m.group(1)
        
        reader = urlopen("http://v.youku.com/player/getPlayList/VideoIDS/%s/" % vid)
        
        inf = json.loads(reader.read())
        
        if (inf is not None) and ("data" in inf) and (len(inf["data"]) > 0):
            
            inf = inf["data"][0]
        
            segs = inf["segs"]
            
            if "hd2" in segs:
                
                ftype = "hd2"
            
            elif "flv" in segs:
                
                ftype = "flv"
            
            elif "mp4" in segs:
                
                ftype = "mp4"
            
            else:
                
                return None
            
            ret["size"] = inf["streamsizes"][ftype]
        
            ret["timelength"] = inf["seconds"] * 1000
            
            ret["name"] = inf["title"]
            
            ret["format"] = ftype
            
            field = inf["streamfileids"][ftype]
                
            urls = []
            
            i = 0
                
            segs = segs[ftype]
            
            for seg in segs:
                
                urls.append(_url(i, inf["seed"], field, seg["k"], ftype)) 
                
                i = i + 1
        
            if len(urls) > 0:
                
                ret["urls"] = urls

                print "{:>20}".format("MisacaYoukuResolver") + ": Found valid youku video '%s'" % ret['name']
        
                #for itm in ret['urls']:
            
                    #print "{:>20}".format("MisacaYoukuResolver") + ": Found urls '%s'" % itm
            
    return ret if len(ret) > 0 else None

def _url(seg, seed, field, key, ftype):
    
    dic = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890'''

    v1 = 0.0
    v2 = ""
    v3 = ""
    
    for i in range(68):
        
        seed = (seed * 211 + 30031) % 65536
        v1 = int(float(seed) / 65536 * (68 - i))
        v2 = dic[v1]
        v3 = v3 + v2
        dic = dic.replace(v2, "");
    
    v4 = 0
    v5 = field.split("*")
    v6 = ""
    v7 = len(v5) - 1
    
    for i in range(v7):
        
        v4 = int(v5[i])
        v6 = v6 + v3[v4]
        
    v8 = hex(seg)[2:]
    
    v8 = ("0" if len(v8) == 1 else "") + v8
    
    return "http://f.youku.com/player/getFlvPath/sid/00_00/st/" + ftype + "/fileid/" + v6[0:8] + v8 + v6[10:] + "?K=" + key

